package com.zline.foodraise.ui.fragment;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.RaiseShopOrderAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.CfOrderBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.CanChildScrollUpCallback;
import com.zline.foodraise.listener.OrderManagerFragmentListener;
import com.zline.foodraise.listener.RecyclerItemClicked;
import com.zline.foodraise.listener.RecyclerOnScrollListener;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.ScrollSwipeRefreshLayout;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by heshantao on 16/1/10.
 * 筹店中送货上门
 */
@EFragment(R.layout.fragment_raise_shop_orders)
public class DeliveryHomeFragment extends Fragment implements CanChildScrollUpCallback, RecyclerItemClicked {
    private static final String LOG_TAG = DeliveryHomeFragment.class.getSimpleName();
    @ViewById(R.id.order_list_srl)
    ScrollSwipeRefreshLayout swipeRefreshLayout;
    @ViewById(R.id.order_list_recyclerView)
    RecyclerView recyclerView;
    //订单总数量
    @ViewById(R.id.order_num_tv)
    TextView order_num_tv;
    LinearLayoutManager layoutManager;
    @Bean
    RaiseShopOrderAdapter adapter;
    SparseArray<CfOrderBean> orders;
    Context cxt;
    @Bean
    HttpUtil httpUtil;
    @Bean
    HttpOperator httpOperator;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    //当前页
    int currt_page = 1;
    //共多少页
    int pageCount;
    @Bean
    HttpDataParsing httpDataParsing;
    //订单Id
    @FragmentArg
    long projectId;
    //订单筛选条件app业务中的众筹订单状态 0:不限 1:已付款 2:待处理 3:已处理 4:无效订单
    @FragmentArg
    int selectStatus;
    //是否是所有众筹项目的订单
    @FragmentArg
    boolean allProjectOrder;
    @FragmentArg
    long userId;
    //全部订单
    static final int RECEIVERY_TYPE_DELIVERY_HOME = 2;
    @ViewById(R.id.exception_rl)
    RelativeLayout exception_rl;
    @ViewById(R.id.ex_no_data_rl)
    RelativeLayout no_data_rl;
    @Bean
    NetworkUtil networkUtil;
    //是否加载失败
    boolean loadFail = false;
    //第一次加载数据
    boolean firstLoad = true;
    //加载更多
    boolean loadMore = false;
    boolean reLoad = false;
    //想要处理的订单position
    int handlerPosition;
    OrderManagerFragmentListener listener;

    @AfterViews
    void doSomeAfterView() {
        cxt = getActivity();
        orders = new SparseArray<CfOrderBean>();
        initView();
        requestData();
    }


    //是否加载失败显示重新加载页面
    void showLoadFailView(boolean isException) {
        loadFail = isException;
        if (isException) {
            exception_rl.setVisibility(View.VISIBLE);
            order_num_tv.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
        } else {
            exception_rl.setVisibility(View.GONE);
            order_num_tv.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.VISIBLE);
        }
        no_data_rl.setVisibility(View.GONE);
    }

    //是否显示暂无数据
    void showNoDataView(boolean noData) {
        if (noData) {
            no_data_rl.setVisibility(View.VISIBLE);
            order_num_tv.setVisibility(View.GONE);
        } else {
            no_data_rl.setVisibility(View.GONE);
            order_num_tv.setVisibility(View.VISIBLE);
        }
        exception_rl.setVisibility(View.GONE);
    }


    void initView() {
        initSwipRefreshLayout();
        initRecyclerView();
    }

    void requestData() {
        if (networkUtil.isNetworkAvailable()) {
            requestProjectOrderList();
        } else {
            showLoadFailView(true);
            TUtil.showShort(cxt, R.string.no_network);
        }
    }

    //底部订单类型切换时候重新加载数据
    public void changeSelectStatus(int status) {
        selectStatus = status + 1;
        //检查网络
        if (networkUtil.isNetworkAvailable()) {
            currt_page = 1;
            swipeRefreshLayout.setRefreshing(true);
            adapter.setRecycleFlag(selectStatus);
            requestProjectOrderList();
        } else {
            showLoadFailView(true);
            TUtil.showShort(cxt, R.string.no_network);
        }
    }

    //设置fragment监听器
    public void setFragmentListener(OrderManagerFragmentListener orderManagerFragmentListener) {
        this.listener = orderManagerFragmentListener;
    }


    //请求筹订单列表
    void requestProjectOrderList() {
        if (allProjectOrder) {
            httpOperator.requestUserProjectOrderList(httpUtil, userId, RECEIVERY_TYPE_DELIVERY_HOME, selectStatus,
                    Constant.PAGE_ROWS_NUMBER, currt_page, requestProjectOrderListHandler);
        } else {
            httpOperator.requestProjectOrderList(httpUtil, projectId, RECEIVERY_TYPE_DELIVERY_HOME, selectStatus,
                    Constant.PAGE_ROWS_NUMBER, currt_page, requestProjectOrderListHandler);
        }
    }


    //获取筹订单列表回调
    AsyncHttpResponseHandler requestProjectOrderListHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestProjectOrderListHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        orders = httpDataParsing.getProjectOrderList(response);
                        getPageCount(response);
                        setOrderTotleCount(response);
                        if (swipeRefreshLayout.isRefreshing() || reLoad) {
                            refreshData(orders);
                        } else {
                            loadMoreData(orders);
                        }
                    } else {
                        loadFailInfo();
                        if (firstLoad) {
                            showLoadFailView(true);
                        } else {
                            httpErro.showCommonErroResult(resultCode);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    firstLoad = false;
                    reLoad = false;
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            if (firstLoad) {
                showLoadFailView(true);
            }
            loadFailInfo();

        }
    };


    //请求处理筹订单
    void requestHandlerProjectOrder(long orderId) {
        if (networkUtil.isNetworkAvailable()) {
            httpOperator.requestHandlerProjectOrder(httpUtil, projectId, requestHandlerProjectOrderHandler);
        } else {
            TUtil.showShort(cxt, R.string.no_network);
        }
    }


    //获取处理订单回调
    AsyncHttpResponseHandler requestHandlerProjectOrderHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestHandlerProjectOrderHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        marketOrder();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    };

    //将订单标记为已处理
    void marketOrder() {
        adapter.getArrys().remove(handlerPosition);
        adapter.notifyItemRemoved(handlerPosition);
        isNoDataException();
    }


    //初始化RecyclerView
    void initRecyclerView() {
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(cxt);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter.setAdapterData(orders);
        //用于标识是付款-未处理等状态
        adapter.setRecycleFlag(selectStatus);
        adapter.setRecycleItemClickListener(this);
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                if (currt_page < pageCount) {
                    //检查网络
                    if (networkUtil.isNetworkAvailable()) {
                        currt_page++;
                        loadMore = true;
                        showRecyclerFoot(true);
                        requestProjectOrderList();

                    } else {
                        TUtil.showShort(cxt, R.string.no_network);
                    }
                }

            }
        });
    }

    //初始化SwipRefreshLayout
    void initSwipRefreshLayout() {
        //设置加载颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeRefreshLayout.setCanChildScrollUpCallback(this);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //检查网络
                if (networkUtil.isNetworkAvailable()) {
                    currt_page = 1;
                    requestProjectOrderList();
                } else {
                    stopRefresh();
                    TUtil.showShort(cxt, R.string.no_network);

                }

            }
        });
    }


    //停止刷新
    void stopRefresh() {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    //刷新数据
    void refreshData(SparseArray<CfOrderBean> orderArray) {
        if (loadFail) {
            showLoadFailView(false);
        }
        adapter.setAdapterData(orderArray);
        adapter.notifyDataSetChanged();
        stopRefresh();
        isNoDataException();
    }

    //加载更多数据
    void loadMoreData(SparseArray<CfOrderBean> orderArray) {
        loadMore = false;
        if (currt_page == pageCount) {
            showRecyclerFoot(false);
        }
        if (loadFail) {
            showLoadFailView(false);
        }
        adapter.addAll(orderArray);
        if (currt_page == 1) {
            isNoDataException();
        }
    }

    //是否显示暂时没有数据
    void isNoDataException() {
        int size = adapter.getArrys().size();
        if (size == 0) {
            showNoDataView(true);
            if (selectStatus == 2) {
                listener.hasUnHandlerOrder(false);
            }
        } else {
            showNoDataView(false);
            if (selectStatus == 2) {
                listener.hasUnHandlerOrder(true);
            }
        }
    }

    //是否显示正在加载
    void showRecyclerFoot(boolean bol) {
        if (adapter != null) {
            adapter.setFootEnable(bol);
            adapter.notifyItemChanged(adapter.getArrys().size());
        }
    }

    //加载失败时候情况处理
    void loadFailInfo() {
        stopRefresh();
        if (loadMore) {
            currt_page--;
        }
        if (adapter.getFootEnable()) {
            showRecyclerFoot(false);
        }
        firstLoad = false;
    }

    //分页查找共多少页
    @Background
    void getPageCount(JSONObject json) {
        try {
            JSONObject jsonObject = json.getJSONObject(Constant.CF_ORDER_BEAN_PAGE);
            pageCount = jsonObject.getInt(Constant.PAGE_COUNT);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //设置订单总数
    void setOrderTotleCount(JSONObject json) {
        try {
            JSONObject jsonObject = json.getJSONObject(Constant.CF_ORDER_BEAN_PAGE);
            int orderCount = jsonObject.getInt(Constant.TOTAL_COUNT);
            String orderCountStr = cxt.getString(R.string.order_num_hint, orderCount);
            order_num_tv.setText(orderCountStr);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Click({R.id.reload_tv})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.reload_tv:
                reLoad = true;
                requestData();
                break;
            default:
                break;
        }
    }


    @Override
    public boolean canSwipeRefreshChildScrollUp() {
        int childCount = recyclerView.getChildCount();
        if (childCount <= 0) {
            return false;
        } else {
            return recyclerView.getChildAt(0).getTop() < Constant.RECYLCERVIEW_SCROLL_Y;
        }
    }

    @Override
    public void onRecyclerItemClicked(int position) {
        handlerPosition = position;
        CfOrderBean orderBean = adapter.getArrys().get(position);
        if (orderBean != null) {
            long orderId = orderBean.getCfOrderId();
            requestHandlerProjectOrder(orderId);
        }
    }

    @Override
    public void onRecyclerItemClicked(int flag, int position) {

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position, int parent) {

    }

    @Override
    public void onRecyclerClickedDelete(int position) {

    }
}
